package com.lagou.demo.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.io.StringReader;
import java.util.Properties;

/**
 * @Description 数据库连接池配置类
 * @Author 郭汝诚
 * @Date 2020/7/26 11:44
 * @Version 1.0
 **/
@Component
public class DataSourceConfig {

    @Autowired
    private CuratorFramework client;

    @Value("${dataSourcePath}")
    private String dataSourcePath;

    @Bean
    public DataSource dataSource() {

        DruidDataSource dataSource = new DruidDataSource();
        try {
            Stat stat = new Stat();
            //从zookeeper数据源配置节点读取数据源配置信息
            byte[] bytes = client.getData().storingStatIn(stat).forPath(dataSourcePath);
            String context = new String(bytes);
            Properties properties = new Properties();
            //将配置信息转换成Properties对象
            properties.load(new StringReader(context));
            //读取Properties对象属性值，填充到dataSource中
            dataSource.setUrl(properties.getProperty("url"));
            dataSource.setUsername(properties.getProperty("username"));
            dataSource.setPassword(properties.getProperty("password"));
            dataSource.setDriverClassName(properties.getProperty("driver-class-name"));
        } catch (Exception e){
            e.printStackTrace();
        }
        return dataSource;
    }

}
